package main

import (
	"log"
	"os"
	"secure-comm/handlers"
	"secure-comm/middleware"
	"secure-comm/pkg/crypto"

	"github.com/gin-gonic/gin"
	"github.com/joho/godotenv"
)

func main() {
	// 加载环境变量
	if err := godotenv.Load(); err != nil {
		log.Println("Warning: .env file not found")
	}

	// 初始化加密参数
	aesKey := os.Getenv("AES_KEY")
	aesIv := os.Getenv("AES_IV")
	if aesKey == "" || aesIv == "" {
		log.Fatal("AES_KEY and AES_IV must be set in environment variables")
	}
	crypto.InitCrypto(aesKey, aesIv)

	// 设置Gin模式
	ginMode := os.Getenv("GIN_MODE")
	if ginMode != "" {
		gin.SetMode(ginMode)
	}

	// 创建Gin实例
	r := gin.Default()

	// 添加CORS中间件
	r.Use(func(c *gin.Context) {
		c.Header("Access-Control-Allow-Origin", "*")
		c.Header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
		c.Header("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Encrypted")
		c.Header("Access-Control-Expose-Headers", "X-Encrypted, Content-Type")
		
		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(204)
			return
		}
		
		c.Next()
	})

	// 健康检查端点（不加密）
	r.GET("/ping", handlers.Ping)

	// API路由组（使用加密中间件）
	api := r.Group("/api")
	api.Use(middleware.SecureCommunication())
	{
		// 认证相关
		api.POST("/login", handlers.Login)
		
		// 用户信息相关
		api.GET("/user", handlers.GetUserInfo)
		api.PUT("/user", handlers.UpdateUserInfo)
	}

	// 获取端口
	port := os.Getenv("PORT")
	if port == "" {
		port = "8080"
	}

	log.Printf("Server starting on port %s", port)
	if err := r.Run(":" + port); err != nil {
		log.Fatal("Failed to start server:", err)
	}
}
